package com.pvdnc.systemdebugger.userauth;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.util.Log;

import com.pvdnc.systemdebugger.compacter.IAuth;
import com.pvdnc.systemdebugger.compacter.PBServiceManager;
import com.pvdnc.systemdebugger.compacter.PBServiceManagerProxy;
import com.pvdnc.systemdebugger.compacter.utils.AppContext;

import java.lang.reflect.Method;

public class KAService extends Service {
    private static final String TAG="KAService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private static boolean SERVICE_STARTED=false;

    public static void startSelf(){
        if(SERVICE_STARTED)
            return;
        Context appContext= AppContext.getAppContext();
        if(appContext==null){
            Log.e(TAG,"fail to start service because appContext is null");
            return;
        }
        appContext.startService(new Intent(appContext,KAService.class));
    }

    private Notification buildForegroundNotification() {
        Notification.Builder builder = new Notification.Builder
                (this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, AuthMainActivity.class);
        //nfIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        builder.setContentIntent(PendingIntent.
                getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher_round)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("Auth") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("Auth KAService is running") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        return notification;
    }

    private void bindAuthByAMS(){
        //手动发送连接请求，确保创建远程服务
        Intent authServiceIntent=new Intent(AppContext.getAppContext(),AuthService.class);
        ServiceConnection serviceConnection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d(TAG,"bind request:"+name.flattenToString());
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d(TAG,"unbind request:"+name.flattenToString());
            }
        };
        bindService(authServiceIntent,serviceConnection,Context.BIND_AUTO_CREATE);
        Log.d(TAG,"bind AuthService by AMS finished");
    }

    private void bindAuthByServiceManager(){
        try {
            Method addService= PBServiceManager.class.getDeclaredMethod("addServiceImpl", String.class, IBinder.class);
            addService.invoke(null,IAuth.SELF_SERVICE_NAME,new Auth());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static final int FOREGROUND_ID=112;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SERVICE_STARTED=true;
        //startForeground(0,new Notification());
        Log.d(TAG,"start to add auth service");
        try {
            PBServiceManagerProxy pbServiceManagerProxy = PBServiceManager.getSelf();
            pbServiceManagerProxy.addService(IAuth.SELF_SERVICE_NAME, new Auth());
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof NullPointerException){

            }
            //bindAuthByAMS();
        }
        Log.d(TAG,"auth service prepared");
        startForeground(FOREGROUND_ID,buildForegroundNotification());
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        SERVICE_STARTED=false;
    }
}
